﻿using IRepository;
using IRepository.DefaultApp;
using IRepository.SystemDefault;
using Microsoft.Extensions.DependencyInjection;
using Model.CustomApp;
using Repository;
using Repository.DefaultApp;
using Repository.SystemDefault;
using System;
using System.Reflection;

namespace Service
{
    /// <summary>
    /// 服务管理，统一在这里注册应用所需要的服务
    /// </summary>
    public class ServiceManager
    {
        private static ServiceProvider service = null;
        static ServiceManager()
        {
            //注册服务
            service = new ServiceCollection()
                .AddSingleton<IDataQueueRepository, DataQueueRepository>()
                .AddSingleton<ICollectInfoConfigRepository, CollectInfoConfigRepository>()
                .AddSingleton<ICollectorUrlRepository, CollectorUrlRepository>()
                .AddSingleton<IHttpConfigRepository, HttpConfigRepository>()
                .AddSingleton<IPageInfoRepository, PageInfoRepository>()
                .AddSingleton<IProxyIPRepository, ProxyIPRepository>()
                .AddSingleton<ICollectorTaskRepository, CollectorTaskRepository>()
                .AddSingleton<IDefaultPageInfoRepository, DefaultPageInfoRepository>()
                .AddSingleton<IAnalyerConfigRepository, AnalyerConfigRepository>()
                .AddSingleton<ICollectorConfigRepository, CollectorConfigRepository>()
                .AddSingleton<IUrlCheckerConfigRepository, UrlCheckerConfigRepository>()
                .AddSingleton<ISetupConfigRepository, SetupConfigRepository>()
                .AddSingleton<ITerminalConfigRepository, TerminalConfigRepository>()

                .AddSingleton<IDefaultRepository<StandardcnDetailModel>, DefaultRepository<StandardcnDetailModel>>()
                .AddSingleton<IDefaultRepository<StdGovStdDetailModel>, DefaultRepository<StdGovStdDetailModel>>()
                .BuildServiceProvider();
        }
        public static T GetService<T>()
        {
            var type = typeof(T);
            //对于直接调用默认的泛型仓储，直接创建对应的对象而不需要麻烦做多余的注册
            if (type.IsGenericType && type.FullName.StartsWith("IRepository.IDefaultRepository`1"))
            {
                var types = type.GetGenericArguments();
                var baseRepositoryType = Assembly.LoadFrom("Repository.dll").GetType("Repositories.DefaultRepository`1");// GetTypes().Where(t=>t.Name.Equals("BaseRepository`1")).FirstOrDefault();
                if (baseRepositoryType != null)
                {
                    var t = baseRepositoryType.MakeGenericType(types);
                    return (T)Activator.CreateInstance(t);
                }
                return default(T);
            }
            else
                return service.GetService<T>();
        }

    }
}
